/**
 * 
 */
package com.admin.his.config;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Path;
import javax.validation.metadata.ConstraintDescriptor;

import com.admin.his.common.exception.ThisSystemException;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * @author 张三
 *
 */
@ControllerAdvice
@SuppressWarnings("rawtypes")
public class GlobleExceptionHandler {

	
	
	@ExceptionHandler
	public ResponseEntity handleOtherException(Throwable e) {
		e.printStackTrace();
		return ResponseEntity.status(599).build();
	}
	
	
	@ExceptionHandler
	public ResponseEntity handleOtherException(ThisSystemException e) {
		Map<String,Object> map=new HashMap<String, Object>(2,1);
		map.put("which",e.getCode());
		map.put("message",e.getMessage());
		return ResponseEntity.badRequest().body(map);
	}
	
	
	@ExceptionHandler
	public ResponseEntity handleValidateException(ConstraintViolationException e) throws IOException{
		Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
		StringBuilder message=new StringBuilder();
		String which=null;
		for (ConstraintViolation<?> cv : constraintViolations) {
			message.append(cv.getMessage());
			Path path=cv.getPropertyPath();
			//获取最后一部分
			for(Path.Node node:path) {
				which=node.getName();
			}
		}
		Map<String,Object> map=new HashMap<String, Object>(2,1);
		map.put("which",which);
		map.put("message",message);
		return ResponseEntity.status(400).body(map);
	}
}
